// import AMap from "AMap";
import { Button, message } from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import styles from "./index.less";

let map;
let marker;

@connect((state) => ({
  menu: state.menu,
  creditCar: state.creditCar,
}))
export default class CreditCarLocation extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
  };

  state = {
    requestPositionTimes: 0,
    issuedLocationBtnLoading: false,
    address: "",
    countDown: 0,
  };
  componentDidMount() {
    this.initMap();
    const vin = sessionStorage.getItem("vin");
    this.handleGetrequestpositionTimes(vin);//获取可下发次数
    this.handleGetcreditstatus(vin);//获取车辆位置。经纬度
  }

  componentWillUnmount() {
    sessionStorage.removeItem("warningRecordUuuid");
    clearInterval(this.timer);
  }

  handleGetrequestpositionTimes = (vin) => {
    this.props.dispatch({
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/position/request/times/get",
        vin: vin,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          this.setState({
            requestPositionTimes: response.data,
          });
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  handleGetcreditstatus = (vin) => {
    this.props.dispatch({
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/position/get",
        vin: vin,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data) {
            this.initMap(response.data.lng, response.data.lat);
            this.setState({
              address: response.data.address,
            });
          }
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };
  handleGetcreditstatus2 = (vin) => {
    this.props.dispatch({
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/position/get",
        vin: vin,
        waitTime: 60,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data) {
            this.initMap(response.data.lng, response.data.lat);
            this.setState({
              address: response.data.address,
            });
          }
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  componentWillMount() {}

  handleOnReturn = () => {
    const backPath = sessionStorage.getItem("creditCarLocationbackPath");
    this.props.dispatch(
      routerRedux.push({
        pathname: backPath,
      })
    );
  };

  handleIssuedLocation = () => {
    const vin = sessionStorage.getItem("vin");
    const businessId = sessionStorage.getItem("warningRecordUuuid");
    const businessCode = sessionStorage.getItem("businessCode");
    this.setState({
      issuedLocationBtnLoading: true,
    });
    const params = {
      vin,
      businessId,
      businessCode,
    };
    this.props.dispatch({
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/position/request",
        ...params,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          // message.success("下发位置成功");
          let countDown = 60;
          this.timer = setInterval(() => {
            countDown--;
            this.setState({ countDown });
            if (countDown === 5) {
              // //同步车辆
              // this.props.dispatch({
              //   type: "extendForm/list",
              //   payload: { url: "/creditvehicle/sync/companycar" },
              // });
            }
            if (countDown === 0) {
              this.setState({
                issuedLocationBtnLoading: false,
              });
              clearInterval(this.timer);
              this.handleGetrequestpositionTimes(vin);
              this.handleGetcreditstatus2(vin);
            }
          }, 1000);
        } else {
          this.setState({
            issuedLocationBtnLoading: false,
          });
          // message.error(response.statusMessage);
        }
      },
    });
  };

  initMap = (lon, lat) => {
    if ((lon, lat)) {
      let obj = this.bd_decrypt(lon, lat);
      map = new AMap.Map("container", {
        resizeEnable: true,
        center: [obj.longitude, obj.latitude],
        zoom: 15,
      });

      marker = new AMap.Marker({
        map: map,
        position: [obj.longitude, obj.latitude],
        icon: require("@/assets/credit_car.png"),
        offset: new AMap.Pixel(-26, -13),
        autoRotation: true,
      });
    } else {
      map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 17,
      });
    }
  };

  /**
   * 百度坐标转高德坐标
   * @param lon
   * @param lat
   * @returns {{lng: number, lat: number}}
   */
  bd_decrypt = (lon, lat) => {
    let X_PI = (Math.PI * 3000.0) / 180.0;
    let x = lon - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
    let gg_lng = z * Math.cos(theta);
    let gg_lat = z * Math.sin(theta);
    return { longitude: gg_lng, latitude: gg_lat };
  };

  render() {
    const {
      requestPositionTimes,
      issuedLocationBtnLoading,
      address,
      countDown,
    } = this.state;
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    const isssuedBtnAuth = permissions.includes(pathname + '/' + 'creditCarLocation_isssued');
    console.log('111111', isssuedBtnAuth)
    return (
      <div className={styles.root}>
        <div className={styles.topBtn}>
          <div className={styles.left}>
            车辆位置：
            <div className={styles.carLocation}>{address}</div>
            <div className={styles.locationBtn}>
              {isssuedBtnAuth ? (
                <Button
                  loading={issuedLocationBtnLoading}
                  disabled={requestPositionTimes === 0}
                  type="primary"
                  onClick={() => this.handleIssuedLocation()}
                >
                  {issuedLocationBtnLoading
                    ? countDown
                      ? "loading(" + countDown + "S)"
                      : "loading"
                    : "获取位置"}
                </Button>
              ) : null}
            </div>
            <div className={styles.issueNumber}>
              今日还可以获取{requestPositionTimes}次
            </div>
          </div>
          <Button type="primary" onClick={() => this.handleOnReturn()}>
            返回
          </Button>
        </div>
        <div className={styles.midMap}>
          <div id="container" style={{ width: "100%", height: "650px" }}></div>
        </div>
      </div>
    );
  }
}
